import { Button, Input, InputNumber, Message, Popover, Radio, Select, Tabs } from '@arco-design/web-react';
import AddressParse from 'address-parse';
import dayjs from 'dayjs';
import { useEffect, useMemo, useState } from 'react';
import { ValidateRule } from '../../../types';
import { copyToClipboard } from '../../../utils/utils';
import DetailModal from '../../../components/detailModal';
import { confirmDialog } from '../../../components/dialog';
import LoadingMask from '../../../components/loadingMask';
import UploadImg from '../../../components/uploadImg';
import { dictDataOptions, getDict,validTel,validateCardId } from '../../../utils/utils';
import { areaList, cityList, provinceList, validateField } from '../../../utils/utils';
import { CardConvertEmConfig,CardConvertLink, CardConvertOrderProduct,PayCouponCardUser,CardDetail } from '../../../types';
import {
  apiGetCardDetailConvertOrderDetailByIccid,
  apiGetEmConfigProductList,
  apiGetProductByConvertOrderType,
  apiUpdateCardDetailConvertOrderDetail,
} from '../../../api';
import { CardDetailConvertOrder } from './types';
import DetailItem from '../../../components/detailItem';
interface Props {
  item: CardDetail;
  onCancel: (update?: boolean) => void;
}
interface CouponSumItem {
  name: string;
  count: number;
  used: number;
  expired: number;
  expireStr: string;
  premiseAmount?: string;
  reduceAmount?: string;
}
interface SelectOption {
  label: string | number;
  value: string | number;
}
/** 流量卡 设备卡禁发省 */
const stopProvince: string[] = ['云南', '新疆', '西藏', '广西'];
/** 流量卡 设备卡禁发市 */
const stopCity: string[] = ['茂名市'];
/** 流量卡 设备卡禁发区 */
const stopArea: string[] = [];

const rule: ValidateRule = {
  orderWay: { required: true, message: '下单方式必填' },
  needPayAmount: { required: true, message: '补差价必填' },
  payAmount: { required: 'needPayAmount', needPayAmount: 'Y', number: true, message: '差价金额必填' },
  provinceName: { required: 'orderWay', orderWay: 'system', message: '省份必填' },
  cityName: { required: 'orderWay', orderWay: 'system', message: '城市必填' },
  countyName: { required: 'orderWay', orderWay: 'system', message: '县/区必填' },
  receiverAddress: { required: 'orderWay', orderWay: 'system', message: '收件地址必填' },
  receiverName: { required: 'orderWay', orderWay: 'system', message: '收件人最少两个字' },
  definedPhotoImg: {
    required: 'orderWay&isDefinedPhoto',
    orderWay: 'system',
    isDefinedPhoto: 'Y',
    message: '该项必填',
  },
  jstGoodsNo: { required: true, message: '供应商必填' },
  receiverPhone: {
    required: 'orderWay',
    orderWay: 'system',
    regexp: /^1[2-9]{1}[0-9]{9}$/,
    message: '联系电话格式错误',
  },
  idName: { required: 'convertType&orderWay', orderWay: 'system', convertType: 'phone', message: '身份证名必填' },
  idNumber: { required: 'convertType&orderWay', orderWay: 'system', convertType: 'phone', message: '身份证号必填' },
  idFrontUrl: { required: 'needIdCard&orderWay', orderWay: 'system', needIdCard: 'Y', message: '身份证国徽面必填' },
  idReverseUrl: { required: 'needIdCard&orderWay', orderWay: 'system', needIdCard: 'Y', message: '身份证人像面必填' },
  faceUrl: { required: 'needIdCard&orderWay', orderWay: 'system', needIdCard: 'Y', message: '手持身份证必填' },
  businessJson: {
    _obj: true,
    cardProductId: { required: true, message: '请选择产品' },
  },
};
const SYS_YES_NO = 'sys_yes_no';
/** 转换类型 号卡phone 设备卡em 流量卡flow */
const CARD_DETAIL_CONVERT_ORDER_CONVERT_TYPE = 'card_detail_convert_order_convert_type';
/** 下单方式 代下单system  客户下单client */
const CARD_DETAIL_CONVERT_ORDER_ORDER_WAY = 'card_detail_convert_order_order_way';
/** 供应商 流量卡 */
const CARD_DETAIL_CONVERT_ORDER_FLOW_JST_GOODS_NO = 'card_detail_convert_order_flow_jst_goods_no';
/** 供应商 设备 */
const CARD_CONVERT_ORDER_EM_JST_GOODS_NO = 'card_convert_order_em_jst_goods_no';
/** 供应商 号卡 */
const CARD_CONVERT_ORDER_PHONE_JST_GOODS_NO = 'card_convert_order_phone_jst_goods_no';
/** 补贴方式 */
const CARD_DETAIL_CONVERT_ORDER_RED_PACKET_TYPE = 'card_detail_convert_order_red_packet_type';

/** 订单状态 已完结success 已支付Y 处理中process 待支付N 取消cancel  退款return */
const CARD_DETAIL_CONVERT_ORDER_STATUS = 'card_detail_convert_order_status';
export default function CardTransferAnyCreateDialog({ item, onCancel }: Props) {
  
  const [dictDatas, setDictDatas] = useState<Record<string, any>>({});
  useEffect(() => {
      async function fetchDictData() {
        const data = await getDict(
          SYS_YES_NO,
          CARD_DETAIL_CONVERT_ORDER_ORDER_WAY,
          CARD_DETAIL_CONVERT_ORDER_CONVERT_TYPE,
          CARD_DETAIL_CONVERT_ORDER_FLOW_JST_GOODS_NO,
          CARD_CONVERT_ORDER_EM_JST_GOODS_NO,
          CARD_DETAIL_CONVERT_ORDER_STATUS,
          CARD_DETAIL_CONVERT_ORDER_RED_PACKET_TYPE,
          CARD_CONVERT_ORDER_PHONE_JST_GOODS_NO
        );
        setDictDatas(data);
      }
  
      fetchDictData();
    }, []);
  const [detailData, setDetailData] = useState<CardDetailConvertOrder>({});
  const [errorData, setErrorData] = useState<{ [x: string]: any }>({});

  // --------------额外数据--------------------------------------
  //自动识别地址填写的内容
  const [readAddress, setReadAddress] = useState('');
  // 流量卡产品
  const [flowProductList, setFlowProductList] = useState<CardConvertOrderProduct[]>([]);
  // 号卡产品
  const [phoneProductList, setPhoneProductList] = useState<CardConvertOrderProduct[]>([]);
  // 设备供应商-产品
  const [emProductList, setEmProductList] = useState<CardConvertEmConfig[]>([]);
  const [linkData, setLinkData] = useState<CardConvertLink>();
  // 可用省份
  const canUseProvinceList = useMemo(() => {
    let list = provinceList();
    let _stopProvice = stopProvince;
    if (detailData?.convertType === 'phone' && detailData?.businessJson?.cardProductId) {
      let product = phoneProductList.find((item) => item.productId === detailData?.businessJson?.cardProductId);

      if (product?.stopProvince?.length) {
        _stopProvice = product.stopProvince!.split(',');
      }
    }
    if (_stopProvice.length) {
      list = list.filter((item) => {
        let canUse = true;
        _stopProvice.forEach((stop) => {
          if (item.includes(stop) && !!stop) {
            canUse = false;
          }
        });
        return canUse;
      });
    }

    return list;
  }, [detailData?.convertType, detailData?.businessJson?.cardProductId]); // eslint-disable-line

  // 可用城市
  const canUseCityList = useMemo(() => {
    let list = cityList(detailData?.provinceName);

    let _stopCity = stopCity;
    if (detailData?.convertType === 'phone' && detailData?.businessJson?.cardProductId) {
      let product = phoneProductList.find((item) => item.productId === detailData?.businessJson?.cardProductId);
      if (product?.stopCity?.length) {
        _stopCity = product.stopCity!.split(',');
      }
    }
    if (_stopCity.length) {
      list = list.filter((item) => {
        let canUse = true;
        _stopCity.forEach((stop) => {
          if (item.includes(stop) && !!stop) {
            canUse = false;
          }
        });
        return canUse;
      });
    }
    return list;
  }, [detailData?.provinceName, detailData?.convertType]); // eslint-disable-line
  // 可用县区
  const canUseAreaList = useMemo(() => {
    let list = areaList(detailData?.provinceName, detailData?.cityName);
    let _stopArea = stopArea;
    if (detailData?.convertType === 'phone' && detailData?.businessJson?.cardProductId) {
      let product = phoneProductList.find((item) => item.productId === detailData?.businessJson?.cardProductId);
      if (product?.stopCounty?.length) {
        _stopArea = product.stopCounty!.split(',');
      }
    }
    if (_stopArea.length) {
      list = list.filter((item) => {
        let canUse = true;
        _stopArea.forEach((stop) => {
          if (item.includes(stop) && !!stop) {
            canUse = false;
          }
        });
        return canUse;
      });
    }

    return list;
  }, [detailData.cityName, detailData?.convertType]); // eslint-disable-line
  // -----------------------------------------------------------

  useEffect(() => {
    loadOldConvertOrder();
  }, [detailData?.convertType]); // eslint-disable-line
  useEffect(() => {
    setBaseField();
  }, []); // eslint-disable-line

  async function loadOldConvertOrder() {
    try {
      let res = await apiGetCardDetailConvertOrderDetailByIccid({
        iccId: item.iccid!,
        convertType: detailData?.convertType ?? 'phone',
      });
      let data = res.data;
      if (data.code === 200) {
        if (data.data?.id) {
          let linkData = data.data;
          setLinkData(linkData);
        } else {
          setLinkData(undefined);
        }
      }
    } catch (e) {}
  }

  function setBaseField(type?: string) {
    let data: CardDetailConvertOrder = {
      balance: (item.cardDetailWallet?.availableAmount ?? 0).toString(),
      needBalance: 'N',
      cardId: item.id,
      iccid: item.iccid,
      userId: item.userId,
      userName: item.userName,
      bonusAmount: 0,
      convertType: type ?? 'phone',
      needPayAmount: 'N',
      orderWay: 'client',
      needIdCard: 'N',
      jstGoodsNo: type === 'flow' ? 'GD003-JDY' : undefined,
      businessJson: {
        cardProductId: undefined,
        cardProductName: undefined,
        cardProductPrice: '0',
      },
    };
    setErrorData({});
    setDetailData(data);
    loadProductList(data.convertType!);
  }

  /**
   * 获取流量卡产品列表
   */
  async function loadProductList(type: string) {
    if (type === 'flow' && !!flowProductList.length) return;
    if (type === 'em' && !!emProductList.length) return;
    if (type === 'phone' && !!phoneProductList.length) return;

    try {
      if (type === 'em') {
        let res = await apiGetEmConfigProductList();
        let data = res.data;
        if (data.code === 200) {
          setEmProductList(data.data ?? []);
        } else {
          Message.warning(data.msg ?? '获取产品列表失败');
        }
      } else {
        let res = await apiGetProductByConvertOrderType(type, item.iccid!);
        let data = res.data;
        if (data.code === 200) {
          if (type === 'flow') {
            setFlowProductList(data.data);
          } else if (type === 'phone') {
            setPhoneProductList(data.data);
          }
        } else {
          Message.warning(data.msg ?? '获取产品列表失败');
        }
      }
    } catch (e: any) {
      Message.error(e.message ?? '获取产品列表失败');
    }
  }

  function handleChange(
    key: string,
    value: any,
    secondKey?: string,
    secondValue?: any,
    therdKey?: string,
    therdValue?: any,
    jsonKey?: string,
    fourKey?: string,
    fourValue?: any
  ) {
    let data: any = { ...detailData };
    if (jsonKey) {
      if (!data[jsonKey]) {
        data[jsonKey] = {};
      }
      data[jsonKey][key] = value;
      if (secondKey) {
        data[jsonKey][secondKey] = secondValue;
      }
      if (therdKey) {
        data[jsonKey][therdKey] = therdValue;
      }
    } else {
      data[key] = value;
      if (secondKey) {
        data[secondKey] = secondValue;
      }
      if (therdKey) {
        data[therdKey] = therdValue;
      }
      if (fourKey) {
        data[fourKey] = fourValue;
      }
    }

    let _balance = parseFloat((data.balance ?? 0).toString());
    let _price = parseFloat((data.businessJson?.cardProductPrice ?? 0).toString());
    // 售价变动
    if (
      key === 'cardProductPrice' ||
      (data.convertType === 'em' && key === 'jstGoodsNo') ||
      (data.convertType !== 'em' && key === 'businessJson')
    ) {
      if (_balance <= 0 && _price > 0) {
        // 余额为0 售价大于0
        data.remark = '物料全款购买';
        data.needPayAmount = 'Y';
        data.payAmount = _price;
        data.orderWay = 'client';
      }
      if (_balance > 0 && _price > 0) {
        // 余额大于0 售价大于0
        if (_balance >= _price) {
          // 余额大于等于售价
          data.needBalance = 'Y';
          data.needPayAmount = 'N';
          data.remark = '全部物料费由余额抵扣';
        } else {
          // 余额小于售价
          data.needBalance = 'Y';
          data.needPayAmount = 'Y';
          data.orderWay = 'client';
          data.payAmount = _price - _balance;
          data.remark = `余额抵扣后补${data.payAmount.toFixed(2)}元物料费。`;
        }
      }
    }
    if (key === 'receiverName' && data.convertType === 'phone') {
      data.idName = value;
    }
    if (key === 'needBalance') {
      if (value !== 'Y') {
        data.payAmount = parseFloat((data.businessJson?.cardProductPrice ?? 0).toString());
        if (_price > 0) {
          data.remark = '物料全款购买';
        } else {
          data.remark = '';
        }
      } else {
        if (_balance >= _price) {
          data.payAmount = 0;
          data.remark = '全部物料费由余额抵扣';
        } else {
          data.payAmount = _price - _balance;
          data.remark = `余额抵扣后补${data.payAmount.toFixed(2)}元物料费。`;
        }
      }
    }
    // 清空地址 避免提前选了禁发地
    if (key === 'convertType' || (key === 'businessJson' && data.convertType === 'phone')) {
      data.provinceName = '';
      data.cityName = '';
      data.countyName = '';
    }
    setDetailData(data);
  }

  // 开始识别地址
  async function handleReadAddress() {
    let [res] = AddressParse.parse(readAddress, true);
    if (res) {
      let _data = Object.assign({}, detailData, {
        provinceName: res.province,
        cityName: res.city,
        countyName: res.area,
        receiverName: res.name,
        receiverPhone: res.mobile ?? res.phone,
        receiverAddress: res.details,
      });
      setDetailData(_data);
    }
  }

  // 确认按钮点击事件
  async function handleConfirm() {
    let validateRes = validateField(detailData, rule);
    if (detailData?.orderWay === 'system') {
      if ((detailData.receiverName?.length ?? 0) < 2) {
        validateRes.receiverName = '收件人最少两个字';
      }
      if (!validTel(detailData.receiverPhone ?? '')) {
        validateRes.receiverPhone = '联系电话格式错误';
      }
      if (detailData?.convertType === 'phone' && !validateCardId(detailData?.idNumber ?? '')) {
        validateRes.idNumber = '身份证格式错误';
      }
    }
    setErrorData(validateRes);
    if (!!Object.keys(validateRes).length) return;
    let useLinkData: CardDetailConvertOrder | undefined;
    let msg = '';
    try {
      LoadingMask.show('正在申请...');
      let res = await apiUpdateCardDetailConvertOrderDetail(detailData?.id?.toString() ?? 'create', detailData);
      let data = res.data;
      useLinkData = data.data;
      if (data.code === 200) {
        msg = data.msg || '申请成功';
        // Message.success('申请成功');
        onCancel(true);
      } else {
        msg = data.msg ?? '申请失败';
        // Message.error(data.msg ?? '申请失败');
      }
    } catch (e: any) {
      msg = e.message ?? '申请失败';
      // Message.error(e.message ?? '申请失败');
    } finally {
      LoadingMask.hide();
    }
    if (!!useLinkData?.id) {
      let t = useLinkData!.convertType === 'flow' ? '流量卡' : useLinkData!.convertType === 'em' ? '设备' : '号卡';
      await confirmDialog({
        title: `【${useLinkData!.iccid}】转${t}`,
        content: (
          <div className="bw-100">
            <div className="d-flex-r">
              <span className="w-80 text-default-color">申请结果</span>
              <span className="flex-1 text-second-color">{msg ?? useLinkData!.orderStatusStr}</span>
            </div>
            <div className="d-flex-r">
              <span className="w-80 text-default-color">推荐资费</span>
              <span className="flex-1 text-second-color">{useLinkData!.businessJson?.cardProductName}</span>
            </div>
            <div className="d-flex-r">
              <span className="w-80 text-default-color">资费售价</span>
              <span className="flex-1 text-second-color">{useLinkData!.businessJson?.cardProductPrice}</span>
            </div>
            <div className="d-flex-r">
              <span className="w-80 text-default-color">补贴金额</span>
              <span className="flex-1 text-second-color">{useLinkData!.bonusAmount}</span>
            </div>
            <div className="d-flex-r">
              <span className="w-80 text-default-color">转换链接</span>
              <span className="flex-1 text-second-color word-wrap">{useLinkData.shortUrl}</span>
            </div>
          </div>
        ),
        hideCancel: true,
        okText: '复制链接并关闭',
      });
      copyToClipboard(useLinkData?.shortUrl || '');
    } else {
      Message.warning(msg);
      onCancel();
    }
  }
  // 提交申请
  function linkRender() {
    if (!linkData) return;
    return (
      <div className="bw-100 mt-10 pl-10">
        <div className="d-flex-r">
          <span className="w-80 text-default-color">申请结果</span>
          <span className="flex-1 text-red-color">{linkData.orderStatusStr}</span>
        </div>
        <div className="d-flex-r">
          <span className="w-80 text-default-color">推荐资费</span>
          <span className="flex-1 text-second-color">{linkData!.businessJson?.cardProductName}</span>
        </div>
        <div className="d-flex-r">
          <span className="w-80 text-default-color">资费售价</span>
          <span className="flex-1 text-second-color">{linkData!.businessJson?.cardProductPrice}</span>
        </div>
        <div className="d-flex-r">
          <span className="w-80 text-default-color">补贴金额</span>
          <span className="flex-1 text-second-color">{linkData!.bonusAmount}</span>
        </div>
        <div className="d-flex-r">
          <span className="w-80 text-default-color">转换链接</span>
          <span className="flex-1 text-second-color word-wrap">{linkData.shortUrl}</span>
        </div>
      </div>
    );
  }

  let productOptions: SelectOption[] = [];
  let tmpProductList: CardConvertOrderProduct[] = [];
  if (detailData?.convertType === 'flow') {
    tmpProductList = flowProductList;
  } else if (detailData?.convertType === 'phone') {
    tmpProductList = phoneProductList;
  }
  productOptions = tmpProductList.map((item) => {
    return {
      label: item.productName!,
      value: item.productId!,
    };
  });
  let emJstGoodsNoOptions: SelectOption[] = [];
  if (detailData?.convertType === 'em') {
    emJstGoodsNoOptions = emProductList.map((item) => {
      let dictItem = dictDatas[CARD_CONVERT_ORDER_EM_JST_GOODS_NO].find((i:any) => i.dictValue === item.operatorType);
      return {
        label: dictItem?.dictLabel + '-' + item.emPrice,
        value: item.jstGoodsNo!,
      };
    });
    if (!!detailData?.jstGoodsNo) {
      let item = emProductList.find((item) => item.jstGoodsNo === detailData?.jstGoodsNo);
      if (item) {
        productOptions = (item.businessJson ?? []).map((item) => {
          return {
            label: item.productName!,
            value: item.productId!,
          };
        });
      }
    }
  }
  function handleCopy() {
    copyToClipboard(linkData?.shortUrl!);
    onCancel();
  }

  let couponList: PayCouponCardUser[] = item.payCouponCardUsers ?? [];
  couponList = couponList.filter((item) => item.couponType === 'payment' && item.status === 'Y');
  let couponMap: { [x: string]: CouponSumItem } = {};
  for (let item of couponList) {
    let expireStr =
      item.expireType === 'fix'
        ? dayjs(item.validEndTime).format('YYYY/MM/DD HH:mm')
        : `${(item.validDays ?? 0) - (dayjs().diff(dayjs(item.createTime), 'day') ?? 0)}天`;
    let str = item.couponName + expireStr;
    if (!couponMap[str]) {
      couponMap[str] = {
        name: item.couponName!,
        count: 0,
        used: 0,
        expired: 0,
        expireStr: expireStr,
        premiseAmount: item.premiseAmount,
        reduceAmount: item.reduceAmount,
      };
    }
    couponMap[str].count += 1;
    if (item.status === 'Y') {
      couponMap[str].used += 1;
    } else if (item.status === 'expired') {
      couponMap[str].expired += 1;
    }
  }
  let couponSumList = Object.values(couponMap);

  couponSumList = couponSumList.filter((citem) => citem.used > 0);

  let _balance = parseFloat((detailData?.balance ?? 0).toString());
  let _price = parseFloat((detailData?.businessJson?.cardProductPrice ?? 0).toString());
  return (
    <DetailModal
      className="bw-80"
      show
      title={`【${item.iccid}】转卡申请`}
      onCancel={onCancel}
      onConfirm={() => {
        !linkData ? handleConfirm() : handleCopy();
      }}
    >
      <Tabs
        className="bw-100"
        activeTab={detailData.convertType}
        onChange={!!detailData?.id && detailData?.id !== 'create' ? undefined : setBaseField}
      >
        <Tabs.TabPane key="phone" title="转换号卡"></Tabs.TabPane>
        <Tabs.TabPane key="flow" title="转流量卡"></Tabs.TabPane>
        <Tabs.TabPane key="em" title="转换设备"></Tabs.TabPane>
      </Tabs>
      {/* {!!detailData?.id && <div className="p-10 text-red-color font-12">已提交过申请，不可更换转换方式</div>} */}
      {!!linkData ? (
        <div>{linkRender()}</div>
      ) : (
        <div className="bw-100 d-flex-r flex-wrap mt-20">
          <DetailItem label="旧充值卡号" labelSpan={8} outlet={2} error={errorData?.cardNo}>
            {detailData?.iccid}
          </DetailItem>
          <DetailItem label="卡余额" labelSpan={10} outlet={couponSumList.length ? 1 : 2} error={errorData?.cardPwd}>
            {item.cardDetailWallet?.availableAmount ?? 0}元
          </DetailItem>
          {!!couponSumList.length && (
            <DetailItem label="优惠券" labelSpan={10} outlet={couponSumList.length ? 1 : 2} error={errorData?.cardPwd}>
              <Popover
                position="tl"
                style={{ maxWidth: '520px' }}
                content={
                  <div>
                    <div className="d-flex-r border-bottom pb-10 mb-10 font-widget-600">
                      <div className="w-180 pl-10">优惠券名称</div>
                      <div className="w-180 pl-10">满减条件</div>
                      <div className="w-80">总数</div>
                      <div className="w-80">已使用</div>
                      <div className="w-80">已过期</div>
                      <div className="w-100">过期时间</div>
                    </div>
                    {couponSumList.map((i, idx) => (
                      <div key={idx} className="d-flex-r border-bottom pb-10 mb-10">
                        <div className="w-180 omit-text pl-10">{i.name}</div>
                        <div className="w-180 omit-text pl-10">
                          {!!i.premiseAmount && !!i?.reduceAmount ? `满${i.premiseAmount}减${i?.reduceAmount}元` : '--'}
                        </div>
                        <div className="w-80 omit-text">{i.count}</div>
                        <div className="w-80 omit-text">{i.used}</div>
                        <div className="w-80 omit-text">{i.expired}</div>
                        <div className="w-100 omit-text">{i.expireStr}</div>
                      </div>
                    ))}
                  </div>
                }
              >
                <span className="ml-5 text-primary-color cursor-pointer">明细</span>
              </Popover>
            </DetailItem>
          )}
          {detailData?.convertType === 'em' && (
            <DetailItem label="供应商" required labelSpan={4} outlet={4} error={errorData?.jstGoodsNo}>
              <Select
                className="m-select"
                showSearch
                filterOption={(iv, option) =>
                  option.props.children.includes(iv) || option.props.value.toLowerCase().includes(iv.toLowerCase())
                }
                options={emJstGoodsNoOptions}
                value={detailData?.jstGoodsNo}
                onChange={(v) => {
                  let item = emProductList.find((item) => item.jstGoodsNo === v);
                  let json = {};
                  if (item && item.businessJson?.length) {
                    json = {
                      cardProductId: item.businessJson![0].productId,
                      cardProductName: item.businessJson![0].productName,
                      cardProductPrice: item.emPrice,
                    };
                  }
                  handleChange('jstGoodsNo', v, 'businessJson', json);
                }}
              />
            </DetailItem>
          )}
          {detailData?.convertType !== 'em' && (
            <DetailItem label="推荐资费" labelSpan={4} outlet={4} error={errorData?.businessJson?.cardProductId}>
              <Select
                className="m-select"
                showSearch
                filterOption={(iv, option) =>
                  option.props.children.includes(iv) || option.props.value.toLowerCase().includes(iv.toLowerCase())
                }
                options={productOptions}
                value={detailData?.businessJson?.cardProductId}
                onChange={(v, option: any) => {
                  let price = '0';
                  let needIdCard = 'N';
                  let jstGoodsNo = detailData?.jstGoodsNo;
                  let isDefinedPhoto = 'N';
                  if (detailData?.convertType === 'phone') {
                    let item = phoneProductList.find((item) => item.productId === v);

                    price = item?.productPrice?.toString() ?? '0';
                    needIdCard = item?.ifPhoto ?? 'N';
                    jstGoodsNo = item?.operatorsType;
                    isDefinedPhoto = item?.isDefinedPhoto ?? 'N';
                  } else {
                    let item = flowProductList.find((item) => item.productId === v);
                    price = item?.productPrice?.toString() ?? '0';
                  }

                  let json = {
                    cardProductId: v,
                    cardProductName: option.children,
                    cardProductPrice: price,
                  };
                  handleChange(
                    'businessJson',
                    json,
                    'needIdCard',
                    needIdCard,
                    'jstGoodsNo',
                    jstGoodsNo,
                    undefined,
                    'isDefinedPhoto',
                    isDefinedPhoto
                  );
                }}
              />
            </DetailItem>
          )}

          <DetailItem label="售价" labelSpan={4} outlet={4} error={errorData?.businessJson?.cardProductPrice}>
            <InputNumber
              precision={2}
              min={0}
              className="m-input"
              disabled={detailData?.convertType === 'em'}
              value={detailData?.businessJson?.cardProductPrice}
              onChange={(v) =>
                handleChange('cardProductPrice', v, undefined, undefined, undefined, undefined, 'businessJson')
              }
            />
          </DetailItem>

          {detailData?.convertType !== 'em' && (
            <DetailItem
              label={detailData?.convertType === 'phone' ? '运营商' : '供应商'}
              required
              labelSpan={4}
              outlet={4}
              error={errorData?.jstGoodsNo}
            >
              <Select
                className="m-select"
                showSearch
                filterOption={(iv, option) =>
                  option.props.children.includes(iv) || option.props.value.toLowerCase().includes(iv.toLowerCase())
                }
                disabled={detailData?.convertType === 'phone'}
                options={dictDataOptions(
                  dictDatas[
                    detailData?.convertType === 'flow'
                      ? CARD_DETAIL_CONVERT_ORDER_FLOW_JST_GOODS_NO
                      : CARD_CONVERT_ORDER_PHONE_JST_GOODS_NO
                  ]
                )}
                value={detailData?.jstGoodsNo}
                onChange={(v) => handleChange('jstGoodsNo', v)}
              />
            </DetailItem>
          )}
          {detailData?.convertType === 'em' && (
            <DetailItem label="推荐资费" labelSpan={4} outlet={4} error={errorData?.businessJson?.cardProductId}>
              <Select
                className="m-select"
                showSearch
                filterOption={(iv, option) =>
                  option.props.children.includes(iv) || option.props.value.toLowerCase().includes(iv.toLowerCase())
                }
                options={productOptions}
                value={detailData?.businessJson?.cardProductId}
                onChange={(v, option: any) => {
                  let price = '0';
                  let needIdCard = 'N';
                  let item = emProductList.find((item) => item.jstGoodsNo === detailData?.jstGoodsNo);
                  if (item) {
                    price = item?.emPrice?.toString() ?? '0';
                  }
                  let json = {
                    cardProductId: v,
                    cardProductName: option.children,
                    cardProductPrice: price,
                  };
                  handleChange('businessJson', json, 'needIdCard', needIdCard);
                }}
              />
            </DetailItem>
          )}
          {_price > 0 && _balance > 0 && (
            <DetailItem label="余额抵扣" labelSpan={4} outlet={4} error={errorData?.needBalance}>
              <Radio.Group
                options={dictDataOptions(dictDatas[SYS_YES_NO])}
                value={detailData?.needBalance}
                onChange={(v) => handleChange('needBalance', v)}
              />
            </DetailItem>
          )}
          <DetailItem
            label="是否支付"
            required
            labelSpan={4}
            outlet={4}
            tips={
              '用户是否需要支付金额' + (detailData?.needPayAmount === 'Y' ? '，需要支付请在保存后复制支付链接' : '')
            }
            error={errorData?.needPayAmount}
          >
            <Radio.Group
              disabled={_price > 0 && _price > _balance}
              options={dictDataOptions(dictDatas[SYS_YES_NO])}
              value={detailData?.needPayAmount}
              onChange={(v) =>
                handleChange('needPayAmount', v, 'orderWay', v === 'Y' ? 'client' : detailData?.orderWay)
              }
            />
          </DetailItem>
          {detailData?.needPayAmount === 'Y' && (
            <DetailItem
              label="订单金额"
              required
              labelSpan={4}
              outlet={4}
              tips="需要用户支付的金额"
              error={errorData?.payAmount}
            >
              <InputNumber
                precision={2}
                min={0}
                suffix="元"
                className="m-input"
                value={detailData?.payAmount}
                onChange={(v) => handleChange('payAmount', v)}
              />
            </DetailItem>
          )}
          <DetailItem label="补贴金额" labelSpan={8} outlet={2} tips="补贴给用户的钱" error={errorData?.bonusAmount}>
            <InputNumber
              precision={2}
              min={0}
              className="m-input"
              value={detailData?.bonusAmount}
              onChange={(v) => handleChange('bonusAmount', v)}
            />
          </DetailItem>
          {Number(detailData?.bonusAmount ?? 0) > 0 && (
            <>
              <DetailItem label="补贴方式" labelSpan={8} outlet={2}>
                <Radio.Group
                  value={detailData?.redPacketType}
                  options={dictDataOptions(dictDatas[CARD_DETAIL_CONVERT_ORDER_RED_PACKET_TYPE])}
                  onChange={(v) => handleChange('redPacketType', v)}
                />
              </DetailItem>
              {detailData?.redPacketType === 'ali' && (
                <>
                  <DetailItem label="支付宝账号" labelSpan={8} outlet={2}>
                    <Input
                      className="m-input"
                      value={detailData?.receiptAccount}
                      placeholder="请输入支付宝账号"
                      onChange={(v) => handleChange('receiptAccount', v)}
                    />
                  </DetailItem>
                  <DetailItem label="支付宝名称" labelSpan={8} outlet={2}>
                    <Input
                      className="m-input"
                      value={detailData?.receiptName}
                      placeholder="请输入支付宝名称"
                      onChange={(v) => handleChange('receiptName', v)}
                    />
                  </DetailItem>
                </>
              )}
              {detailData?.redPacketType === 'wx' && (
                <DetailItem label="微信收款码" labelSpan={8} outlet={2}>
                  <UploadImg
                    limit={1}
                    onlyReturnUrl
                    values={detailData?.receiptImg ? [detailData?.receiptImg] : []}
                    onChange={(v) => handleChange('receiptImg', v[0])}
                  />
                </DetailItem>
              )}
            </>
          )}
          {detailData?.needPayAmount !== 'Y' && (
            <DetailItem
              label="下单方式"
              required
              labelSpan={4}
              outlet={4}
              tips={detailData?.orderWay === 'client' ? '请在保存后到换卡申请列表复制链接' : ''}
              error={errorData?.orderWay}
            >
              <Radio.Group
                options={dictDataOptions(dictDatas[CARD_DETAIL_CONVERT_ORDER_ORDER_WAY])}
                value={detailData?.orderWay}
                onChange={(v) => handleChange('orderWay', v)}
              />
            </DetailItem>
          )}

          {detailData?.orderWay === 'system' && (
            <>
              <div className="d-flex-c ai-center bw-100 mb-20">
                <Input.TextArea
                  className="m-input flex-1 mb-20"
                  placeholder="请粘贴地址信息，如果识别不准确，请在姓名和手机号左右加逗号"
                  autoSize={{ minRows: 2 }}
                  value={readAddress}
                  onChange={setReadAddress}
                />
                <Button type="primary" onClick={handleReadAddress}>
                  识别
                </Button>
              </div>
              <DetailItem label="收件人" required labelSpan={8} outlet={2} error={errorData?.receiverName}>
                <Input
                  className="m-input"
                  value={detailData?.receiverName}
                  onChange={(v) => handleChange('receiverName', v)}
                />
              </DetailItem>
              <DetailItem label="联系电话" required labelSpan={8} outlet={2} error={errorData?.receiverPhone}>
                <Input
                  className="m-input"
                  value={detailData?.receiverPhone}
                  onChange={(v) => handleChange('receiverPhone', v)}
                />
              </DetailItem>
              <DetailItem label="省" required labelSpan={8} outlet={2} error={errorData?.provinceName}>
                <Select
                  className="m-select"
                  showSearch
                  filterOption={(inputValue, option) =>
                    option.props.children.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
                  }
                  options={canUseProvinceList}
                  value={detailData?.provinceName}
                  onChange={(v) => handleChange('provinceName', v)}
                />
              </DetailItem>
              <DetailItem label="市" required labelSpan={8} outlet={2} error={errorData?.cityName}>
                <Select
                  className="m-select"
                  showSearch
                  filterOption={(inputValue, option) =>
                    option.props.children.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
                  }
                  options={canUseCityList}
                  value={detailData?.cityName}
                  onChange={(v) => handleChange('cityName', v)}
                />
              </DetailItem>
              <DetailItem label="县/区" required labelSpan={4} outlet={4} error={errorData?.countyName}>
                <Select
                  className="m-select"
                  showSearch
                  filterOption={(inputValue, option) =>
                    option.props.children.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
                  }
                  options={canUseAreaList}
                  value={detailData?.countyName}
                  onChange={(v) => handleChange('countyName', v)}
                />
              </DetailItem>
              <DetailItem label="收件地址" required labelSpan={4} outlet={4} error={errorData?.receiverAddress}>
                <Input.TextArea
                  className="m-input"
                  autoSize={{ minRows: 2 }}
                  value={detailData?.receiverAddress}
                  onChange={(v) => handleChange('receiverAddress', v)}
                />
              </DetailItem>
              {detailData?.convertType === 'phone' && (
                <>
                  <DetailItem label="身份证名" required labelSpan={4} outlet={4} error={errorData?.idName}>
                    <Input className="m-input" value={detailData?.idName} onChange={(v) => handleChange('idName', v)} />
                  </DetailItem>
                  <DetailItem label="身份证号" required labelSpan={4} outlet={4} error={errorData?.idNumber}>
                    <Input
                      className="m-input"
                      value={detailData?.idNumber}
                      onChange={(v) => handleChange('idNumber', v)}
                    />
                  </DetailItem>
                </>
              )}
              {detailData?.convertType === 'phone' && detailData?.needIdCard === 'Y' && (
                <>
                  <DetailItem label="身份证国徽面" required labelSpan={4} outlet={4} error={errorData?.idFrontUrl}>
                    <UploadImg
                      limit={1}
                      onlyReturnUrl
                      values={detailData?.idFrontUrl ? [detailData?.idFrontUrl] : []}
                      onChange={(v) => handleChange('idFrontUrl', v[0])}
                    />
                  </DetailItem>
                  <DetailItem label="身份证人像面" required labelSpan={4} outlet={4} error={errorData?.idReverseUrl}>
                    <UploadImg
                      limit={1}
                      onlyReturnUrl
                      values={detailData?.idReverseUrl ? [detailData?.idReverseUrl] : []}
                      onChange={(v) => handleChange('idReverseUrl', v[0])}
                    />
                  </DetailItem>
                  <DetailItem label="免冠正面照" required labelSpan={4} outlet={4} error={errorData?.faceUrl}>
                    <UploadImg
                      limit={1}
                      onlyReturnUrl
                      values={detailData?.faceUrl ? [detailData?.faceUrl] : []}
                      onChange={(v) => handleChange('faceUrl', v[0])}
                    />
                  </DetailItem>
                </>
              )}
              {detailData?.convertType === 'phone' && detailData?.isDefinedPhoto === 'Y' && (
                <DetailItem label="一证通截图" required labelSpan={4} outlet={4} error={errorData?.definedPhotoImg}>
                  <UploadImg
                    limit={1}
                    onlyReturnUrl
                    values={detailData?.definedPhotoImg ? [detailData?.definedPhotoImg] : []}
                    onChange={(v) => handleChange('definedPhotoImg', v[0])}
                  />
                </DetailItem>
              )}
            </>
          )}
          <DetailItem label="备注" labelSpan={4} outlet={4} error={errorData?.remark}>
            <Input.TextArea
              className="m-input"
              autoSize={{ minRows: 3, maxRows: 3 }}
              value={detailData?.remark}
              onChange={(v) => handleChange('remark', v)}
            />
          </DetailItem>
        </div>
      )}
    </DetailModal>
  );
}
